<?php
/**
 * 档期管理，排期管理
 */
namespace Admin\Controller;
use Admin\BaseController;
use Admin\Model\ScheduleModel;
use Common\Model\UtilsModel;

class ScheduleController extends BaseController{
	public function scheduleList(){
			if(IS_POST) {
				$needEvent = I('post.event', 0, 'intval');
			}else{
				$needEvent = 1;
			}
			$dateRange 	= I('post.dateRange');
			list($startDate,$endDate)=explode(' ~ ',$dateRange);
			if(!$startDate){
				$startDate=date('Y-m-d');
			}


			$timeSTMP = strtotime($startDate);
			$w = date("w",$timeSTMP);
			if($w==0){
				$w=7;
			}
			if($w!=1){
				$startTime = strtotime(1-$w." days",$timeSTMP);
			}else{
				$startTime = $timeSTMP;
			}
			$startDate=date('Y-m-d',$startTime);

			///////////////////////////////////////////////////
			if(!$endDate){
				$endDate=date('Y-m-d',$startTime+UtilsModel::ONE_DAY * 27);
			}




			$timeSTMP = strtotime($endDate);
			$w = date("w",$timeSTMP);
			if($w==0){
				$w=7;
			}
			if($w!=7){
				$endTime =strtotime(7-$w." days",$timeSTMP);
			}else{
				$endTime =$timeSTMP;
			}
			$endDate =date('Y-m-d',$endTime);

			$excludeStatus=ScheduleModel::STATUS_CANCEL;

			$article=ScheduleModel::getArticleInstance()->where("status <>{$excludeStatus} AND publishDate between '{$startDate}' and '{$endDate} 23:59:59'")->select();
			if($needEvent) {
				$event = ScheduleModel::getEventInstance()->where("status <>{$excludeStatus} AND eventDate between '{$startDate}' and '{$endDate} 23:59:59'")->select();
			}

			$articleBindEvent=array();
			foreach($article as $v) {
				$articleBindEvent[]=$v['bindEvent'];
			}
			if(count($articleBindEvent)>0){
				$idstr=implode(',',$articleBindEvent);
				$tmpevents = ScheduleModel::getEventInstance()->where("status <>{$excludeStatus} AND eid in ({$idstr})")->select();
				$bindEevent=array();
				foreach ($tmpevents as $v){
					$bindEevent[$v['eid']]=$v;
				}
				$this->smarty->assign('bindEevent',$bindEevent);
			}

			//显示用
			$weekarray_show=array("日","一","二","三","四","五","六");

			$list=array();
			for($start = $startTime; $start <= $endTime;$start += UtilsModel::ONE_DAY) {
				$tmp=array();
				$tmp['date']=date('Y-m-d', $start);
				$tmp['day']=$weekarray_show[date('w',$start)];
				$tmp[0]		='-1';
				$tmp[1]		='-1';
				$tmp[2]		='-1';
				$tmp[3]		='-1';
				$tmp[4]		='-1';
				$tmp[5]	    ='-1';//活动


				foreach($article as $k=>$v) {
					if($tmp['date']==substr($v['publishDate'],0,10)){
						$tmp[$v['position']] .=','.$k;
					}
				}
				if($needEvent) {
					foreach ($event as $k => $v) {
						if ($tmp['date'] == $v['eventDate']) {
							$tmp[5] .= ',' . $k;
						}
					}
				}
				$list[]=$tmp;
			}


			$pos=array('头条','次一','次二','次三','次四');
			if($needEvent) {
				$pos[]='活动';
			}
			$this->smarty->assign('pos',$pos);
			$this->smarty->assign('list',$list);


			if($needEvent) {
				$this->smarty->assign('event', $event);
			}
			$this->smarty->assign('article',$article);

			$signTypeKv=ScheduleModel::getSignTypeKV();
			$this->smarty->assign('signTypeKv',$signTypeKv);

			$statusKv=ScheduleModel::getStatusKV();
			$this->smarty->assign('statusKv',$statusKv);

			$businessTypeKv=ScheduleModel::getBusinessTypeKV();
			$this->smarty->assign('businessTypeKv',$businessTypeKv);

			if(IS_POST){
				echo $this->smarty->fetch('Schedule/scheduleList_list.html');
			}else{
				$this->smarty->display('Schedule/scheduleList.html');
			}


		}
	public function scheduleTable(){
		$dateRange 	= I('post.dateRange');
		list($startDate,$endDate)=explode(' ~ ',$dateRange);

		$where='1';
		if($startDate){
			$where .=" and publishDate >= '{$startDate}'";
		}
		if($endDate){
			$where .=" and publishDate <= '{$endDate}'";
		}

		$title=I('post.title');
		if($title){
			$where .=" and title like '%{$title}%'";
		}
		$businessType=I('post.businessType',0,'intval');
		if($businessType){
			$where .=" and businessType ={$businessType}";
		}
		$writerName=I('post.writerName');
		if($writerName){
			$where .=" and writerName like '{$writerName}'";
		}


		$operatorName=I('post.operatorName');
		if($operatorName){
			$where .=" and operatorName like '{$operatorName}'";
			$article=ScheduleModel::getArticleInstance()->join(' left join schedule_event on schedule_article.bindEvent=schedule_event.eid')->where($where)->field('schedule_article.*')->select();
		}else{
			$article=ScheduleModel::getArticleInstance()->where($where)->select();
		}



		$articleBindEvent=array();
		foreach($article as $v) {
			$articleBindEvent[]=$v['bindEvent'];
		}
		if(count($articleBindEvent)>0){
			$idstr=implode(',',$articleBindEvent);
			$tmpevents = ScheduleModel::getEventInstance()->where("eid in ({$idstr})")->select();
			$bindEevent=array();
			foreach ($tmpevents as $v){
				$bindEevent[$v['eid']]=$v;
			}
			$this->smarty->assign('bindEevent',$bindEevent);
		}

		$this->smarty->assign('article',$article);

		$statusKv=ScheduleModel::getStatusKV();
		$this->smarty->assign('statusKv',$statusKv);

		$businessTypeKv=ScheduleModel::getBusinessTypeKV();
		$this->smarty->assign('businessTypeKv',$businessTypeKv);

		$positionKv=ScheduleModel::getPlaceKV();
		$this->smarty->assign('positionKv',$positionKv);



		if(IS_POST){
			echo $this->smarty->fetch('Schedule/scheduleTable_list.html');
		}else{
			$userName=ScheduleModel::getUserName();
			$this->smarty->assign('userList',$userName);
			$this->smarty->display('Schedule/scheduleTable.html');
		}


	}
	public function scheduleArticle(){
		if(IS_AJAX){
			$this->scheduleArticleDo();
			return;
		}

		$aid=I('get.aid',0,'intval');
		$needFee = 0;
		if($aid){
			$articleDetail=ScheduleModel::getArticleInstance()->where('aid='.$aid)->find();
			$this->smarty->assign('obj',$articleDetail);

			if($articleDetail['businessType'] == ScheduleModel::BUSINESS_TYPE_FEE || $articleDetail['businessType'] ==ScheduleModel::BUSINESS_TYPE_MIX){
				$needFee = 1;
			}

			if($articleDetail['bindEvent']){
				$this->smarty->assign('evt',ScheduleModel::getEventInstance()->where('eid='.$articleDetail['bindEvent'])->find());
			}
		}

		$this->smarty->assign('needFee',$needFee);

		$signTypeKv=ScheduleModel::getSignTypeKV();
		$this->smarty->assign('signTypeKv',$signTypeKv);

		$statusKv=ScheduleModel::getStatusKV();
		$this->smarty->assign('statusKv',$statusKv);

		$businessTypeKv=ScheduleModel::getBusinessTypeKV();
		$this->smarty->assign('businessTypeKv',$businessTypeKv);

		$placeKv=ScheduleModel::getPlaceKV();
		$this->smarty->assign('placeKv',$placeKv);

		$eventKv=ScheduleModel::getEventInstance()->where('status <>'.ScheduleModel::STATUS_CANCEL)->order('eid desc')->limit('60')->getField('eid,title',true);
		$this->smarty->assign('eventKv',$eventKv);

		$userName=ScheduleModel::getUserName();
		$this->smarty->assign('userList',$userName);

		$this->smarty->assign('statusCandel',ScheduleModel::STATUS_CANCEL);
		$this->smarty->display('Schedule/scheduleArticle.html');
	}
	
	public function scheduleEvent(){
		if(IS_AJAX){
			$this->scheduleEventDo();
			return;
		}

		$eid=I('get.eid',0,'intval');
		if($eid){
			$eventDetail=ScheduleModel::getEventInstance()->where('eid='.$eid)->find();
			$this->smarty->assign('evt',$eventDetail);
		}

		$signTypeKv=ScheduleModel::getSignTypeKV();
		$this->smarty->assign('signTypeKv',$signTypeKv);

		$statusKv=ScheduleModel::getStatusKV();
		$this->smarty->assign('statusKv',$statusKv);

		$userName=ScheduleModel::getUserName();
		$this->smarty->assign('userList',$userName);
		$this->smarty->assign('statusCandel',ScheduleModel::STATUS_CANCEL);


		$this->smarty->display('Schedule/scheduleEvent.html');
	}


	private function scheduleEventDo()
	{
		$return = array(
			'status' => 0,
			'msg' => 'success',
		);
		$bindEventID = I('post.eid', 0, 'intval');
		$now = time();
		$eventData = array(
			'title' => I('post.event_title'),
			'eventDate' => I('post.eventDate'),
			'operatorName' => I('post.operatorName'),
			'signType' => I('post.signType', 0, 'intval'),
			'quota' => I('post.quota'),
			'listSureTime' => I('post.listSureTime'),
			'mem' => I('post.event_mem'),
			'status' => I('post.event_status')
		);

		$eventData['listSureTime'] = strtotime($eventData['listSureTime']);
		if ($eventData['listSureTime'] - $now >= UtilsModel::ONE_HOUR) {
			$eventData['remindStatus'] = 0;
		} else {
			$eventData['remindStatus'] = 1;
		}

		if (!$bindEventID) {
			$bindEventID = ScheduleModel::getEventInstance()->add($eventData);
			if (!$bindEventID) {
				$return['status'] = 1;
				$return['msg'] = '活动创建失败';
				$this->ajaxReturn($return);
			}
		} else {
			$ret = ScheduleModel::getEventInstance()->where('eid=' . $bindEventID)->save($eventData);
			if ($ret == false) {
				$return['status'] = 1;
				$return['msg'] = '活动修改失败';
				$this->ajaxReturn($return);
			}
			if ($eventData['status'] == ScheduleModel::STATUS_CANCEL) {
				ScheduleModel::cancelArticle($bindEventID);
			}
		}
		$this->ajaxReturn($return);
	}

	private function scheduleArticleDo(){
		$return=array(
			'status'=>0,
			'msg'=>'success',
		);
		$aid=I('post.aid',0,'intval');
		$now=time();

		$eventBind=I('post.eventBind',0,'intval');
		switch ($eventBind){
			case ScheduleModel::BIND_EVENT_NONE:
				$bindEventID=0;
				break;
			default:
				$bindEventID=I('post.existEventId',0,'intval');
				$eventData=array(
					'title'=>I('post.event_title'),
					'eventDate'=>I('post.eventDate'),
					'operatorName'=>I('post.operatorName'),
					'signType'=>I('post.signType',0,'intval'),
					'quota'=>I('post.quota'),
					'listSureTime'=>I('post.listSureTime'),
					'mem'=>I('post.event_mem'),
					'status'=>I('post.event_status'),
				);
				$eventData['listSureTime'] = strtotime($eventData['listSureTime']);
				if( $eventData['listSureTime']-$now >= UtilsModel::ONE_HOUR ){
					$eventData['remindStatus'] = 0;
				}else{
					$eventData['remindStatus'] = 1;
				}

				if($eventBind==ScheduleModel::BIND_EVENT_NEW){
					$bindEventID=ScheduleModel::getEventInstance()->add($eventData);
					if(!$bindEventID){
						$return['status']=1;
						$return['msg']='活动创建失败';
						$this->ajaxReturn($return);
					}else{
						$return['eid']=$bindEventID;
						$return['eventTitle']=$eventData['title'];
					}
				}elseif($eventBind==ScheduleModel::BIND_EVENT_OLD){
					$ret=ScheduleModel::getEventInstance()->where('eid='.$bindEventID)->save($eventData);
					if($ret===false){
						$return['status']=1;
						$return['msg']='活动修改失败:'.ScheduleModel::getEventInstance()->getError();
						$this->ajaxReturn($return);
					}
					if($eventData['status']==ScheduleModel::STATUS_CANCEL){
						ScheduleModel::cancelArticle($bindEventID);
					}

				}
				break;
		}


		$data=array(
			'publishDate'=>I('post.publishDate'),
			'title'=>I('post.title'),
			'position'=>I('post.position',0,'intval'),
			'businessType'=>I('post.businessType',0,'intval'),
			'fee'=>I('post.fee',0,'floatval'),
			'needInvoice'=>I('post.needInvoice',0,'intval'),
			'mem'=>I('post.mem'),
			'bindEvent'=>I('post.mem'),
			'writerName'=>I('post.writerName'),
			'status'=>I('post.status',0,'intval'),
			'bindEvent'=>$bindEventID,
			'addTime'=>$now,
		);

		$data['remindTime'] = strtotime($data['publishDate']);
		if( $data['remindTime']-$now >= UtilsModel::ONE_DAY){
			$data['remindStatus'] = 0;
		}else{
			$data['remindStatus'] = 1;
		}

		if (!$aid){//增加
			$ret=ScheduleModel::getArticleInstance()->add($data);
		}else{//修改
			$ret=ScheduleModel::getArticleInstance()->where('aid='.$aid)->save($data);
		}
		if($ret==false){
			$return['msg']='操作失败：'.ScheduleModel::getArticleInstance()->getError();
			$return['status']=1;
		}
		$this->ajaxReturn($return);


	}



	
	
	public function getEventDetail(){
		$eid=I('post.eid',0,'intval');
		$detail=ScheduleModel::getEventInstance()->where('eid='.$eid)->find();
		if(!$detail){
			$this->ajaxReturn(array('status'=>1,'msg'=>'未找到'));
		}else{
			$detail['listSureTime']=date('Y-m-d H:i:s',$detail['listSureTime']);
			$this->ajaxReturn(array('status'=>0,'data'=>$detail));
		}
	}
}
